import axios from 'axios';
import { baseURL } from "../../config/config"
import store from "../store"


import { notification } from 'antd';

axios.defaults.timeout = 5000;
axios.defaults.baseURL = baseURL;
axios.defaults.headers['Content-Type'] = 'application/json';


axios.interceptors.request.use(opt => {
    const userInfo = store.userStore.userInfo;
    if (!!userInfo.username) {
        opt.headers["X-Auth-User"] = userInfo.username;
        opt.headers["X-Auth-Token"] = userInfo.token;
    }
    return opt;
}, error => {
    return Promise.reject(error);
})

axios.interceptors.response.use(response => {
    if (response.data.status.code > 0) {
        notification.error({
            message: response.data.status.message,
            duration: 4
        })
        return Promise.reject(response.data.status.message);
    } else if (response.data.status.code < 0) {
        notification.error({
            message: "网络错误，请稍后再试",
            duration: 4
        })
        return Promise.reject(response.data.status.message);
    }
    return response;
}, error => {
    error.response = error.response || {}
    switch (error.response.status) {
        case 401:
        case 403:
            
            notification.error({
                message: "登陆已失效",
                duration: 2,
                onClose() {
                    store.userStore.loginOut();
                    window.location.href = "/#/login";
                }
            });
            break;
        default:
            notification.error({
                message: "网络错误，请稍后再试",
                duration: 4
            })
            break;
    }
    return Promise.reject(error)
})

export default axios;